from Base import SockerBase


class Client:
    """ 初始化 然后rece文件"""
    def __init__(self, ip='127.0.0.1', port=50000):
        self.sock = SockerBase(ip, port)
        self.sock.init_client()

    def recv(self, my_path, other_path):
        self.sock.print('Before recv')
        self.my_path, self.other_path = my_path, other_path
        if self._recv_check():
            self.sock.print('Start rece file')
            self._do_recv()
            self.sock.print('Success rece file')
        else:
            self.sock.print('Rece file fail')
            return False

    def _recv_check(self):
        return self.check_connect() and self.check_file()

    def check_file(self):
        try:
            with open(self.my_path, 'w'):
                return True
        except FileExistsError:
            self.sock.print('File does not exit')
            return False

    def check_connect(self):
        self.sock.mysend({'path': self.other_path})
        response = self.sock.myrece()
        if not response.get('able', False):
            self.sock.print('Server does not allow this aciton or does not exist')
            self.sock.print('Server msg:', response.get('msg'))
            return False
        else:
            return True

    def _do_recv(self):
        datas = self.sock.myrece()
        with open(self.my_path, 'wb') as f:
            f.write(datas)


if __name__ == '__main__':
    c = Client()
    c.recv('./reced_file', './file')